import {
  Component,
  OnInit,
  Input,
  AfterViewInit,
  Renderer2,
  ViewChild,
  ElementRef,
  ChangeDetectionStrategy,
} from '@angular/core';
export interface CarouselData {
  imageUrl: string;
  caption?: string;
  link: string;
}

@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ImageSliderComponent implements OnInit, AfterViewInit {
  @ViewChild('imgSlider')
  imgSlider!: ElementRef;
  // @ViewChild('imageSliderContainer') imageSliderContainer!: ElementRef;
  @Input() sliders: CarouselData[] = [];
  @Input() time: number = 1;
  public imgIndex: number = 0;
  public position: number = 0;
  public isScroll: boolean = false;
  constructor(private rd2: Renderer2) {}
  carousel(): void {
    setInterval(() => {
      this.rd2.setProperty(
        this.imgSlider.nativeElement,
        'scrollLeft',
        (this.imgIndex++ * this.imgSlider.nativeElement.scrollWidth) /
          this.sliders.length
      );
      if (this.imgIndex < 0 || this.imgIndex > this.sliders.length) {
        this.imgIndex = 0;
      }
      // this.position =
      //   this.imgIndex++ * this.imageSliderContainer.nativeElement.scrollWidth;
      // console.log(this.position);
      // this.rd2.setStyle(
      //   this.imgSlider.nativeElement,
      //   'transform',
      //   `translate3d(-${this.position}px, 0, 0)`
      // );
      // if (this.imgIndex < 0 || this.imgIndex >= this.sliders.length) {
      //   this.imgIndex = 0;
      //   this.position = 0;
      // }
    }, this.time * 1000);
  }
  handleTouchMove(): void {
    this.isScroll = true;
  }
  handleTouched(): void {
    this.isScroll = false;
  }
  handleScroll(e: any) {
    if (this.isScroll) {
      const ratio =
        (e.target.scrollLeft * this.sliders.length) / e.target.scrollWidth;
      this.imgIndex = Math.round(ratio);
    }
    return;
  }
  ngOnInit() {}
  ngAfterViewInit(): void {
    this.carousel();
  }
}
